<script setup lang="ts">
  import { getorgList } from '@/api/syssetting';
  import { getCrdaDetail, editCrdaDetail } from '@/api/archives';
  import { FormInstance, Message } from '@arco-design/web-vue';
  import { deepClone } from '@arco-vue-pro-components/pro-components/es/pro-table/utils';

  const props = defineProps({
    visible: Boolean,
    isEdit: Boolean,
    editParam: Object,
  });
  const emit = defineEmits(['update:visible', 'refresh']);
  const close = () => {
    emit('update:visible', false);
  };
  const formFields = ref({});
  const orgOptions = ref<Array<{
    value: string | number;
    label: string;
  }> | null>(null);
  const formData = reactive({
    room_name: '', //档案室名称 *
    room_number: '', //编号 *
    room_address: '', //位置 *
    room_org_id: '', //所属单位 *
  });
  onMounted(async () => {
    fetchOrgData();
  });
  watch(
    () => props.editParam,
    async (newVal) => {
      try {
        // 清除旧数据
        Object.keys(formData).forEach((key: any) => (formData[key] = ''));

        if (newVal) {
          // 请求机构详情
          const res = await getCrdaDetail({ room_id: newVal });
          // 填充表单数据（安全赋值）
          Object.assign(formData, {
            room_name: res.data.room_name || '',
            room_id: res.data.room_id || '',
            room_number: res.data.room_number || '',
            room_address: res.data.room_address || '',
            room_org_id: res.data.room_org_id || '',
          });
        }
      } catch (error) {}
    },
    { immediate: true } // 初始化时立即执行一次
  );

  const formRef = ref<FormInstance | null>(null);

  const handleSubmit = async () => {
    // if (await formRef.value?.checkForm()) {
    //   Message.error('请正确填写表单！');
    // } else {
    //   addCrda({
    //     ...formRef.value?.formModel,
    //   }).then((res) => {
    //     if (res.code == 200) {
    //       Message.success(res?.msg);
    //       emit('update:visible', false);
    //       emit('refresh');
    //     }
    //   });
    // }
    try {
      await formRef.value?.checkForm();
      editCrdaDetail(formRef.value?.formModel)
        .then((res) => {
          Message.success(res.msg);
          emit('refresh', deepClone(formData));
          close();
        })
        .catch((err) => {});
    } catch (error) {
      // 分类处理错误
      Message.error('请正确填写表单！');
    }
  };

  formFields.value = [
    {
      label: '编号',
      name: 'room_number',
      rules: [
        {
          required: true,
          message: '请输入',
          validateTrigger: ['blur'], // Arco 推荐触发方式
        },
      ],
      fieldProps: {
        placeholder: '请输入',
        allowClear: true,
        maxLength: 200,
        span: 12,
      },
    },
    {
      label: '档案室名称',
      name: 'room_name',
      fieldProps: {
        placeholder: '请输入',
        allowClear: true,
        maxLength: 50,
      },
      tooltip: '软件注册后，请不要随意修改档案室名称，这会导致需要重新注册',
      rules: [
        {
          required: true,
          message: '档案室名称不能为空',
          validateTrigger: ['input'], // Arco 推荐触发方式
        },
        {
          maxLength: 50,
          message: '不能超过50个字符',
          validateTrigger: ['input'],
        },
      ],
    },

    {
      label: '位置',
      name: 'room_address',
      rules: [
        {
          required: true,
          message: '请输入',
          validateTrigger: ['blur'], // Arco 推荐触发方式
        },
      ],
      fieldProps: {
        placeholder: '请输入',
        allowClear: true,
        maxLength: 200,
      },
    },
    {
      name: 'room_org_id',
      label: '所属单位',
      type: 'a-select',
      fieldProps: {
        placeholder: '请选择所属单位',
      },
      selectOptions: orgOptions,
    },
  ];
  // 模拟异步获取组织数据
  const fetchOrgData = async () => {
    const orgdata = await getorgList();
    const filteredData = orgdata.data.list.map((item: any) => ({
      label: item.org_name,
      value: item.org_id,
    }));

    // 更新orgOptions.value为过滤后的数组
    orgOptions.value = filteredData;
  };
</script>
<script lang="ts">
  export default {
    name: 'company',
  };
</script>

<template>
  <a-modal
    title="编辑档案室"
    width="600px"
    :visible="visible"
    title-align="start"
    @Ok="handleSubmit"
    @cancel="close"
  >
    <pro-form
      ref="formRef"
      hiddenBtn
      :form-json="formFields"
      :form-data="formData"
    ></pro-form>
  </a-modal>
</template>

<style scoped lang="less"></style>
